package info.ask4research.web;

import info.ask4research.model.UnitOfLearning;
import info.ask4research.model.activities.Activity;
import info.ask4research.model.addons.Addon;
import info.ask4research.model.addons.MultipleChoice;
import info.ask4research.model.addons.QuestionsAndAnswers;
import info.ask4research.model.addons.TextWork;
import info.ask4research.model.addons.UploadingFiles;
import info.ask4research.model.enums.ServiceType;
import info.ask4research.model.roles.Role;
import info.ask4research.model.toolsAndMaterials.AnnouncementService;
import info.ask4research.model.toolsAndMaterials.ChatService;
import info.ask4research.model.toolsAndMaterials.ForumService;
import info.ask4research.model.toolsAndMaterials.LearningObject;
import info.ask4research.model.toolsAndMaterials.SentMailService;
import info.ask4research.model.toolsAndMaterials.ToolAndMaterial;
import info.ask4research.service.IActivityService;
import info.ask4research.service.IRoleService;
import info.ask4research.service.IToolAndMaterialService;
import info.ask4research.service.IUnitOfLearningService;
import info.ask4research.service.impl.ToolAndMaterialService;
import info.ask4research.web.dto.AddonDTO;
import info.ask4research.web.dto.EditToolAndMaterialDTO;
import info.ask4research.web.dto.ToolsAndMaterialsDTO;
import info.ask4research.web.dto.ToolsAndMaterialsRolesDTO;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ToolsAndMaterialsController {

	private IUnitOfLearningService unitOfLearningService;
	private IToolAndMaterialService toolAndMaterialService;
	private IRoleService roleService;
	private IActivityService activityService;
	

	@RequestMapping(value="jsp/toolsAndMaterials/getTreeToolsAndMaterials.action")
	public @ResponseBody JSON treeTreeaddons(
			@RequestParam(value="node") String node,
			HttpSession session) throws Exception {
		List<ToolsAndMaterialsDTO> tamsDTOs = new ArrayList<ToolsAndMaterialsDTO>();
		int unitOfLearningId = (Integer)session.getAttribute("unitOfLearningId");

		JSON jsonObject = null;
		if(String.valueOf(unitOfLearningId) != null){
			if("lo".equals(node)|| "Tools & Materials/Learning Object".equals(node) ){
				List<LearningObject> listTamss = toolAndMaterialService.getLearningObjectByUoL(unitOfLearningId);
				for(LearningObject learningObject : listTamss){
					ToolsAndMaterialsDTO toolsAndMaterialsDTO = new ToolsAndMaterialsDTO(learningObject);
					toolsAndMaterialsDTO.setText(learningObject.getTitle());
					toolsAndMaterialsDTO.setId("Tools & Materials/Learning Object/"+learningObject.getTitle());
					toolsAndMaterialsDTO.setLeaf(true);
					tamsDTOs.add(toolsAndMaterialsDTO);
				}
			} else if("fs".equals(node)|| "Tools & Materials/Forum Service".equals(node) ){
				List<ForumService> forumServices = toolAndMaterialService.getForumServicesByUoL(unitOfLearningId);
				for(ForumService forumService : forumServices){
					ToolsAndMaterialsDTO toolsAndMaterialsDTO = new ToolsAndMaterialsDTO(forumService);
					toolsAndMaterialsDTO.setText(forumService.getTitle());
					toolsAndMaterialsDTO.setId("Tools & Materials/Forum Service/"+forumService.getTitle());
					toolsAndMaterialsDTO.setLeaf(true);
					tamsDTOs.add(toolsAndMaterialsDTO);
				}
			}else if("as".equals(node)|| "Tools & Materials/Announcement Service".equals(node) ){
				List<AnnouncementService>  announcementServices = toolAndMaterialService.getAnnouncementServiceByUoL(unitOfLearningId);
				for(AnnouncementService announcementService : announcementServices){
					ToolsAndMaterialsDTO toolsAndMaterialsDTO = new ToolsAndMaterialsDTO(announcementService);
					toolsAndMaterialsDTO.setText(announcementService.getTitle());
					toolsAndMaterialsDTO.setId("Tools & Materials/Announcement Service/"+announcementService.getTitle());
					toolsAndMaterialsDTO.setLeaf(true);
					tamsDTOs.add(toolsAndMaterialsDTO);
				}
			} else if("cs".equals(node)|| "Tools & Materials/Chat Service".equals(node) ){
				List<ChatService> chatServices = toolAndMaterialService.getChatServiceByUoL(unitOfLearningId);
				for(ChatService chatService : chatServices){
					ToolsAndMaterialsDTO toolsAndMaterialsDTO = new ToolsAndMaterialsDTO(chatService);
					toolsAndMaterialsDTO.setText(chatService.getTitle());
					toolsAndMaterialsDTO.setId("Tools & Materials/Chat Service/"+chatService.getTitle());
					toolsAndMaterialsDTO.setLeaf(true);
					tamsDTOs.add(toolsAndMaterialsDTO);
				}
			} else if("sm".equals(node)|| "Tools & Materials/Send Mail".equals(node) ){
				List<SentMailService> sentMailServices = toolAndMaterialService.getSentMailServiceByUoL(unitOfLearningId);
				for(SentMailService sentMailService : sentMailServices){
					ToolsAndMaterialsDTO toolsAndMaterialsDTO = new ToolsAndMaterialsDTO(sentMailService);
					toolsAndMaterialsDTO.setText(sentMailService.getTitle());
					toolsAndMaterialsDTO.setId("Tools & Materials/Send Mail/"+sentMailService.getTitle());
					toolsAndMaterialsDTO.setLeaf(true);
					tamsDTOs.add(toolsAndMaterialsDTO);
				}
			}else {
				ToolsAndMaterialsDTO loDTO = new ToolsAndMaterialsDTO();
				loDTO.setText("Learning Object");
				loDTO.setId("Tools & Materials/Learning Object");
				loDTO.setCls("folder");

				ToolsAndMaterialsDTO fsDTO = new ToolsAndMaterialsDTO();
				fsDTO.setText("Forum Service");
				fsDTO.setId("Tools & Materials/Forum Service");
				fsDTO.setCls("folder");

				ToolsAndMaterialsDTO csDTO = new ToolsAndMaterialsDTO();
				csDTO.setText("Chat Service");
				csDTO.setId("Tools & Materials/Chat Service");
				csDTO.setCls("folder");

				ToolsAndMaterialsDTO asDTO = new ToolsAndMaterialsDTO();
				asDTO.setText("Announcement Service");
				asDTO.setId("Tools & Materials/Announcement Service");
				asDTO.setCls("folder");

				ToolsAndMaterialsDTO smDTO = new ToolsAndMaterialsDTO();
				smDTO.setText("Send Mail");
				smDTO.setId("Tools & Materials/Send Mail");
				smDTO.setCls("folder");

				tamsDTOs.add(loDTO);
				tamsDTOs.add(fsDTO);
				tamsDTOs.add(asDTO);
				tamsDTOs.add(csDTO);
				tamsDTOs.add(smDTO);
			}
		}
		JsonConfig jsonConfig = new JsonConfig();
		jsonObject = JSONSerializer.toJSON(tamsDTOs, jsonConfig);
		return jsonObject;
	}


	@RequestMapping(value="jsp/tam/lo.action")
	public @ResponseBody Map<String, Object> saveLearningObjectaddons(
			@RequestParam(value="lo") String lo,
			HttpSession session) throws Exception {
		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		LearningObject learningObject = new LearningObject();
		Map<String,Object> modelMap = new HashMap<String,Object>(3);

		if(unitOfLearning != null ){

			learningObject.setTitle(lo);
			learningObject.setUnitOfLearning(unitOfLearning);

			toolAndMaterialService.save(learningObject);

			modelMap.put("total", 1);
			//modelMap.put("learningObject", learningObject);
			modelMap.put("success", true);
		} else {
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("failure", false);
		}

		return modelMap;
	}

	@RequestMapping(value="jsp/tam/fs.action")
	public @ResponseBody Map<String, Object> saveForumServiceaddons(
			@RequestParam(value="fs") String fs,
			HttpSession session) throws Exception {
		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		ForumService forumService = new ForumService();
		Map<String,Object> modelMap = new HashMap<String,Object>(3);

		if(unitOfLearning != null ){

			forumService.setTitle(fs);
			forumService.setUnitOfLearning(unitOfLearning);

			toolAndMaterialService.save(forumService);

			modelMap.put("total", 1);
			//modelMap.put("forumService", forumService);
			modelMap.put("success", true);
		} else {
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("failure", false);
		}

		return modelMap;
	}

	@RequestMapping(value="jsp/tam/as.action")
	public @ResponseBody Map<String, Object> saveAnnouncementServiceaddons(
			@RequestParam(value="as") String as,
			HttpSession session) throws Exception {
		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		AnnouncementService announcementService = new AnnouncementService();
		Map<String,Object> modelMap = new HashMap<String,Object>(3);

		if(unitOfLearning != null ){

			announcementService.setTitle(as);
			announcementService.setUnitOfLearning(unitOfLearning);

			toolAndMaterialService.save(announcementService);

			modelMap.put("total", 1);
			//modelMap.put("forumService", forumService);
			modelMap.put("success", true);
		} else {
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("failure", false);
		}

		return modelMap;
	}

	@RequestMapping(value="jsp/tam/cs.action")
	public @ResponseBody Map<String, Object> saveChatServiceaddons(
			@RequestParam(value="cs") String cs,
			HttpSession session) throws Exception {
		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		ChatService chatService = new ChatService();
		Map<String,Object> modelMap = new HashMap<String,Object>(3);

		if(unitOfLearning != null ){

			chatService.setTitle(cs);
			chatService.setUnitOfLearning(unitOfLearning);

			toolAndMaterialService.save(chatService);

			modelMap.put("total", 1);
			//modelMap.put("forumService", forumService);
			modelMap.put("success", true);
		} else {
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("failure", false);
		}

		return modelMap;
	}

	@RequestMapping(value="jsp/tam/sm.action")
	public @ResponseBody Map<String, Object> saveSentMailaddons(
			@RequestParam(value="sm") String sm,
			HttpSession session) throws Exception {
		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		SentMailService sentMailService = new SentMailService();
		Map<String,Object> modelMap = new HashMap<String,Object>(3);

		if(unitOfLearning != null ){

			sentMailService.setTitle(sm);
			sentMailService.setUnitOfLearning(unitOfLearning);

			toolAndMaterialService.save(sentMailService);

			modelMap.put("total", 1);
			modelMap.put("success", true);
		} else {
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("failure", false);
		}

		return modelMap;
	}

	@RequestMapping(value="jsp/tam/getAttributes.action")
	public @ResponseBody Map<String, Object> getRoleAttributes(
			@RequestParam(value="tamToEdit") String stringTam,
			HttpSession session) throws Exception {

		int unitOfLearningId = (Integer)session.getAttribute("unitOfLearningId");
		boolean tamExists = toolAndMaterialService.tamNameExists(stringTam,(Integer)session.getAttribute("unitOfLearningId"));
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		if(String.valueOf(unitOfLearningId) != null && tamExists==true){
			ToolAndMaterial tam = toolAndMaterialService.getTaMByUoFandTamName(stringTam,unitOfLearningId);
			EditToolAndMaterialDTO editToolAndMaterialDTO = new EditToolAndMaterialDTO(tam);
			modelMap.put(editToolAndMaterialDTO.getTamInstance(), editToolAndMaterialDTO);
			modelMap.put("total", 1);
			modelMap.put("success", true);
		} else {
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("failure", false);
		}

		return modelMap;
	}

	@RequestMapping(value="jsp/tam/saveLearningObject.action")
	public @ResponseBody Map<String, Object> saveLearningObject(
			@RequestParam(value="description") String description,
			@RequestParam(value="title") String title,
			HttpSession session) throws Exception {

		int unitOfLearningId = (Integer)session.getAttribute("unitOfLearningId");
		boolean tamExists = toolAndMaterialService.tamNameExists(title,(Integer)session.getAttribute("unitOfLearningId"));
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		if(String.valueOf(unitOfLearningId) != null && tamExists==true){
			ToolAndMaterial tam = toolAndMaterialService.getTaMByUoFandTamName(title,unitOfLearningId);
			tam.setDescription(description);
			tam = toolAndMaterialService.save(tam);
			EditToolAndMaterialDTO editToolAndMaterialDTO = new EditToolAndMaterialDTO(tam);
			modelMap.put(editToolAndMaterialDTO.getTamInstance(), editToolAndMaterialDTO);
			modelMap.put("total", 1);
			modelMap.put("success", true);
		} else {
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("failure", false);
		}

		return modelMap;
	}
	
	
	@RequestMapping(value="jsp/tam/fsGrid.action")
	public @ResponseBody Map<String, Object> fsGridView(
			HttpSession session,
			@RequestParam(value="limit",required=false) Integer limit,
			@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="start",required=false) Integer start,
			@RequestParam(value="node",required=false) String node,
			@RequestParam(value="dataFromGrid",required=false) List<String> dataFromGrid) throws Exception {

		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		ForumService tam = (ForumService) toolAndMaterialService.getTaMByUoFandTamName(node,(Integer)session.getAttribute("unitOfLearningId"));
		List<Role> roles = roleService.getRoleListByUoL(1000, 1, 0, unitOfLearning.getId());
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		List<ToolsAndMaterialsRolesDTO> rolesDTO = new ArrayList<ToolsAndMaterialsRolesDTO>();
		if(dataFromGrid==null){
			ToolsAndMaterialsRolesDTO toolsAndMaterialsRolesDTO = new ToolsAndMaterialsRolesDTO(tam,roles);
			tam = (ForumService) toolAndMaterialService.save(tam);
			modelMap.put("uolTitle", unitOfLearning.getTitle());
			modelMap.put("uolId", unitOfLearning.getId());
			modelMap.put("items", toolsAndMaterialsRolesDTO.getRolesDTO());
			modelMap.put("total", toolsAndMaterialsRolesDTO.getRolesDTO().size());
			modelMap.put("success", true);
		}else{
			int listSize = dataFromGrid.size();
			for(int i=0; i<listSize;){
				ToolsAndMaterialsRolesDTO toolsAndMaterialsRolesDTO = new ToolsAndMaterialsRolesDTO();
				toolsAndMaterialsRolesDTO.setRoleName(dataFromGrid.get(i++));
				toolsAndMaterialsRolesDTO.setParticipant(Boolean.valueOf(dataFromGrid.get(i++)));
				toolsAndMaterialsRolesDTO.setObserver(Boolean.valueOf(dataFromGrid.get(i++)));
				rolesDTO.add(toolsAndMaterialsRolesDTO);
			}
			List<Role> participants = new ArrayList<Role>();
			List<Role> observers = new ArrayList<Role>();
			for(ToolsAndMaterialsRolesDTO dto : rolesDTO){
				Role role = roleService.getRoleByUoFandRoleName(dto.getRoleName(), unitOfLearning.getId());
				if(dto.isObserver()){
					observers.add(role);
				}
				if(dto.isParticipant()){
					participants.add(role);
				}
			}
			tam.setObservers(observers);
			tam.setParticipants(participants);
			toolAndMaterialService.save(tam);
		}
		
		return modelMap;
	}
	
	
	@RequestMapping(value="jsp/tam/asGrid.action")
	public @ResponseBody Map<String, Object> asGridView(
			HttpSession session,
			@RequestParam(value="limit",required=false) Integer limit,
			@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="start",required=false) Integer start,
			@RequestParam(value="node",required=false) String node,
			@RequestParam(value="dataFromGrid",required=false) List<String> dataFromGrid) throws Exception {

		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		AnnouncementService tam = (AnnouncementService) toolAndMaterialService.getTaMByUoFandTamName(node,(Integer)session.getAttribute("unitOfLearningId"));
		List<Role> roles = roleService.getRoleListByUoL(1000, 1, 0, unitOfLearning.getId());
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		List<ToolsAndMaterialsRolesDTO> rolesDTO = new ArrayList<ToolsAndMaterialsRolesDTO>();
		if(dataFromGrid==null){
			ToolsAndMaterialsRolesDTO toolsAndMaterialsRolesDTO = new ToolsAndMaterialsRolesDTO(tam,roles);
			tam = (AnnouncementService) toolAndMaterialService.save(tam);
			modelMap.put("uolTitle", unitOfLearning.getTitle());
			modelMap.put("uolId", unitOfLearning.getId());
			modelMap.put("items", toolsAndMaterialsRolesDTO.getRolesDTO());
			modelMap.put("total", toolsAndMaterialsRolesDTO.getRolesDTO().size());
			modelMap.put("success", true);
		}else{
			int listSize = dataFromGrid.size();
			for(int i=0; i<listSize;){
				ToolsAndMaterialsRolesDTO toolsAndMaterialsRolesDTO = new ToolsAndMaterialsRolesDTO();
				toolsAndMaterialsRolesDTO.setRoleName(dataFromGrid.get(i++));
				toolsAndMaterialsRolesDTO.setParticipant(Boolean.valueOf(dataFromGrid.get(i++)));
				toolsAndMaterialsRolesDTO.setObserver(Boolean.valueOf(dataFromGrid.get(i++)));
				rolesDTO.add(toolsAndMaterialsRolesDTO);
			}
			List<Role> participants = new ArrayList<Role>();
			List<Role> observers = new ArrayList<Role>();
			for(ToolsAndMaterialsRolesDTO dto : rolesDTO){
				Role role = roleService.getRoleByUoFandRoleName(dto.getRoleName(), unitOfLearning.getId());
				if(dto.isObserver()){
					observers.add(role);
				}
				if(dto.isParticipant()){
					participants.add(role);
				}
			}
			tam.setObservers(observers);
			tam.setParticipants(participants);
			toolAndMaterialService.save(tam);
		}
		
		return modelMap;
	}

	
	@RequestMapping(value="jsp/tam/csGrid.action")
	public @ResponseBody Map<String, Object> csGridView(
			HttpSession session,
			@RequestParam(value="limit",required=false) Integer limit,
			@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="start",required=false) Integer start,
			@RequestParam(value="node",required=false) String node,
			@RequestParam(value="dataFromGrid",required=false) List<String> dataFromGrid) throws Exception {

		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		ChatService tam = (ChatService) toolAndMaterialService.getTaMByUoFandTamName(node,(Integer)session.getAttribute("unitOfLearningId"));
		List<Role> roles = roleService.getRoleListByUoL(1000, 1, 0, unitOfLearning.getId());
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		List<ToolsAndMaterialsRolesDTO> rolesDTO = new ArrayList<ToolsAndMaterialsRolesDTO>();
		if(dataFromGrid==null){
			ToolsAndMaterialsRolesDTO toolsAndMaterialsRolesDTO = new ToolsAndMaterialsRolesDTO(tam,roles);
			tam = (ChatService) toolAndMaterialService.save(tam);
			modelMap.put("uolTitle", unitOfLearning.getTitle());
			modelMap.put("uolId", unitOfLearning.getId());
			modelMap.put("items", toolsAndMaterialsRolesDTO.getRolesDTO());
			modelMap.put("total", toolsAndMaterialsRolesDTO.getRolesDTO().size());
			modelMap.put("success", true);
		}else{
			int listSize = dataFromGrid.size();
			for(int i=0; i<listSize;){
				ToolsAndMaterialsRolesDTO toolsAndMaterialsRolesDTO = new ToolsAndMaterialsRolesDTO();
				toolsAndMaterialsRolesDTO.setRoleName(dataFromGrid.get(i++));
				toolsAndMaterialsRolesDTO.setParticipant(Boolean.valueOf(dataFromGrid.get(i++)));
				toolsAndMaterialsRolesDTO.setObserver(Boolean.valueOf(dataFromGrid.get(i++)));
				rolesDTO.add(toolsAndMaterialsRolesDTO);
			}
			List<Role> participants = new ArrayList<Role>();
			List<Role> observers = new ArrayList<Role>();
			for(ToolsAndMaterialsRolesDTO dto : rolesDTO){
				Role role = roleService.getRoleByUoFandRoleName(dto.getRoleName(), unitOfLearning.getId());
				if(dto.isObserver()){
					observers.add(role);
				}
				if(dto.isParticipant()){
					participants.add(role);
				}
			}
			tam.setObservers(observers);
			tam.setParticipants(participants);
			toolAndMaterialService.save(tam);
		}
		
		return modelMap;
	}
	
	@RequestMapping(value="jsp/tam/smGrid.action")
	public @ResponseBody Map<String, Object> smGridView(
			HttpSession session,
			@RequestParam(value="limit",required=false) Integer limit,
			@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="start",required=false) Integer start,
			@RequestParam(value="node",required=false) String node,
			@RequestParam(value="dataFromGrid",required=false) List<String> dataFromGrid) throws Exception {

		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		SentMailService tam = (SentMailService) toolAndMaterialService.getTaMByUoFandTamName(node,(Integer)session.getAttribute("unitOfLearningId"));
		List<Role> roles = roleService.getRoleListByUoL(1000, 1, 0, unitOfLearning.getId());
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		List<ToolsAndMaterialsRolesDTO> rolesDTO = new ArrayList<ToolsAndMaterialsRolesDTO>();
		if(dataFromGrid==null){
			ToolsAndMaterialsRolesDTO toolsAndMaterialsRolesDTO = new ToolsAndMaterialsRolesDTO(tam,roles);
			tam = (SentMailService) toolAndMaterialService.save(tam);
			modelMap.put("uolTitle", unitOfLearning.getTitle());
			modelMap.put("uolId", unitOfLearning.getId());
			modelMap.put("items", toolsAndMaterialsRolesDTO.getRolesDTO());
			modelMap.put("total", toolsAndMaterialsRolesDTO.getRolesDTO().size());
			modelMap.put("success", true);
		}else{
			int listSize = dataFromGrid.size();
			for(int i=0; i<listSize;){
				ToolsAndMaterialsRolesDTO toolsAndMaterialsRolesDTO = new ToolsAndMaterialsRolesDTO();
				toolsAndMaterialsRolesDTO.setRoleName(dataFromGrid.get(i++));
				toolsAndMaterialsRolesDTO.setRecipient(Boolean.valueOf(dataFromGrid.get(i++)));
				rolesDTO.add(toolsAndMaterialsRolesDTO);
			}
			List<Role> recipients = new ArrayList<Role>();
			for(ToolsAndMaterialsRolesDTO dto : rolesDTO){
				Role role = roleService.getRoleByUoFandRoleName(dto.getRoleName(), unitOfLearning.getId());
				if(dto.isRecipient()){
					recipients.add(role);
				}
			}
			tam.setRecipients(recipients);
			toolAndMaterialService.save(tam);
		}
		
		return modelMap;
	}
	
	@RequestMapping(value="jsp/tam/getAllRoles.action")
	public @ResponseBody Map<String, Object> getAllRoles(
			HttpSession session) throws Exception {

		int unitOfLearningId = (Integer)session.getAttribute("unitOfLearningId");
		List<Role> roles = new ArrayList<Role>();
		roles = roleService.getLearnerRolesByUoL(unitOfLearningId);
		roles.addAll(roleService.getStaffRolesByUoL(unitOfLearningId));
		for(Role role: roles){
			role.setUnitOfLearning(null);
		}
		Map<String,Object> modelMap = new HashMap<String,Object>(3);

		modelMap.put("items", roles);
		modelMap.put("total", roles.size());
		modelMap.put("success", true);


		return modelMap;
	}

	@RequestMapping(value="jsp/tam/saveForumService.action")
	public @ResponseBody Map<String, Object> updateFS(
			HttpSession session,
			@RequestParam(value="decription",required=false) String decription,
			@RequestParam(value="manager",required=false) String manager,
			@RequestParam(value="moderator",required=false) String moderator,
			@RequestParam(value="title",required=false) String title) throws Exception {

		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		Role moderatorRole = roleService.getRoleByUoFandRoleName(moderator, unitOfLearning.getId());
		Role managerRole = roleService.getRoleByUoFandRoleName(manager, unitOfLearning.getId());

		ForumService tam = (ForumService) toolAndMaterialService.getTaMByUoFandTamName(title,(Integer)session.getAttribute("unitOfLearningId"));
		tam.setManager(managerRole);
		tam.setModerator(moderatorRole);
		tam.setDescription(decription);

		ForumService fs = (ForumService) toolAndMaterialService.save(tam);
		Map<String,Object> modelMap = new HashMap<String,Object>(3);

		modelMap.put("uolTitle", unitOfLearning.getTitle());
		modelMap.put("uolId", unitOfLearning.getId());
		modelMap.put("items", fs);
		modelMap.put("total", 1);
		modelMap.put("success", true);


		return modelMap;
	}
	
	@RequestMapping(value="jsp/tam/saveAnnouncementService.action")
	public @ResponseBody Map<String, Object> updateAnnouncementObject(
			HttpSession session,
			@RequestParam(value="decription",required=false) String decription,
			@RequestParam(value="manager",required=false) String manager,
			@RequestParam(value="moderator",required=false) String moderator,
			@RequestParam(value="title",required=false) String title) throws Exception {

		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		Role moderatorRole = roleService.getRoleByUoFandRoleName(moderator, unitOfLearning.getId());
		Role managerRole = roleService.getRoleByUoFandRoleName(manager, unitOfLearning.getId());

		AnnouncementService tam = (AnnouncementService) toolAndMaterialService.getTaMByUoFandTamName(title,(Integer)session.getAttribute("unitOfLearningId"));
		tam.setManager(managerRole);
		tam.setModerator(moderatorRole);
		tam.setDescription(decription);

		AnnouncementService as = (AnnouncementService) toolAndMaterialService.save(tam);
		Map<String,Object> modelMap = new HashMap<String,Object>(3);

		modelMap.put("uolTitle", unitOfLearning.getTitle());
		modelMap.put("uolId", unitOfLearning.getId());
		modelMap.put("items", as);
		modelMap.put("total", 1);
		modelMap.put("success", true);


		return modelMap;
	}
	
	
	@RequestMapping(value="jsp/tam/chatService.action")
	public @ResponseBody Map<String, Object> updateChatObject(
			HttpSession session,
			@RequestParam(value="decription",required=false) String decription,
			@RequestParam(value="manager",required=false) String manager,
			@RequestParam(value="moderator",required=false) String moderator,
			@RequestParam(value="title",required=false) String title) throws Exception {

		int unitOfLearningId = (Integer)session.getAttribute("unitOfLearningId");
		Role moderatorRole = roleService.getRoleByUoFandRoleName(moderator, unitOfLearningId);
		Role managerRole = roleService.getRoleByUoFandRoleName(manager, unitOfLearningId);

		ChatService tam = (ChatService) toolAndMaterialService.getTaMByUoFandTamName(title,unitOfLearningId);
		tam.setManager(managerRole);
		tam.setModerator(moderatorRole);
		tam.setDescription(decription);

		ChatService as = (ChatService) toolAndMaterialService.save(tam);
		Map<String,Object> modelMap = new HashMap<String,Object>(3);

//		modelMap.put("uolTitle", unitOfLearning.getTitle());
//		modelMap.put("uolId", unitOfLearning.getId());
		modelMap.put("items", as);
		modelMap.put("total", 1);
		modelMap.put("success", true);

		return modelMap;
	}
	
	
	@RequestMapping(value="jsp/tam/sentMailService.action")
	public @ResponseBody Map<String, Object> updateSentMailObject(
			HttpSession session,
			@RequestParam(value="all",required=false) ServiceType serviceType,
			@RequestParam(value="title",required=false) String title) throws Exception {

		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		
		SentMailService tam = (SentMailService) toolAndMaterialService.getTaMByUoFandTamName(title,(Integer)session.getAttribute("unitOfLearningId"));
		tam.setServiceType(serviceType);

		SentMailService as = (SentMailService) toolAndMaterialService.save(tam);
		Map<String,Object> modelMap = new HashMap<String,Object>(3);

		modelMap.put("uolTitle", unitOfLearning.getTitle());
		modelMap.put("uolId", unitOfLearning.getId());
		modelMap.put("items", as);
		modelMap.put("total", 1);
		modelMap.put("success", true);

		return modelMap;
	}
	
	
	@RequestMapping(value="jsp/tam/laGrid.action")
	public @ResponseBody Map<String, Object> laGridObject(
			HttpSession session,
			@RequestParam(value="limit",required=false) Integer limit,
			@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="start",required=false) Integer start,
			@RequestParam(value="data",required=false) List<String> data) throws Exception {

		int unitOfLearningId = (Integer)session.getAttribute("unitOfLearningId");
		String activityId = (String)session.getAttribute("graphId");
		String[] activityType = activityId.split(":");
		Activity activity = activityService.getbyGraphId(activityType[1]);
		List<ToolAndMaterial> uolTams = toolAndMaterialService.getTamByUoL(unitOfLearningId);
		List<ToolAndMaterial> activityTams = new ArrayList<ToolAndMaterial>();
		HashMap<Integer, ToolsAndMaterialsDTO> tamsDTOHash = new HashMap<Integer, ToolsAndMaterialsDTO>();
		if(!activity.getTams().isEmpty()){
			activityTams = activity.getTams();
		}
		
		List<ToolsAndMaterialsDTO> tamDTOs = new ArrayList<ToolsAndMaterialsDTO>();
		if(data==null){//just view them
			if(!activityTams.isEmpty()){
				for(ToolAndMaterial tam : activityTams){
					ToolsAndMaterialsDTO tamDTO = new ToolsAndMaterialsDTO();
					tamDTO.setText(tam.getTitle());
					tamDTO.setId(String.valueOf(tam.getId()));
					tamDTO.setEnable(true);
					if(tam instanceof LearningObject){
						tamDTO.setType("LearningObject");
					}else if(tam instanceof ForumService){
						tamDTO.setType("ForumService");
					}else if(tam instanceof AnnouncementService){
						tamDTO.setType("AnnouncementService");
					}else if(tam instanceof ChatService){
						tamDTO.setType("ChatService");
					}else if(tam instanceof SentMailService){
						tamDTO.setType("SentMailService");
					}
					tamsDTOHash.put(tam.getId(), tamDTO);
				}
				
				for(ToolAndMaterial tam : uolTams){
					if(!tamsDTOHash.containsKey(tam.getId())){
						ToolsAndMaterialsDTO tamDTO = new ToolsAndMaterialsDTO();
						tamDTO.setText(tam.getTitle());
						tamDTO.setId(String.valueOf(tam.getId()));
						tamDTO.setEnable(false);
						if(tam instanceof LearningObject){
							tamDTO.setType("LearningObject");
						}else if(tam instanceof ForumService){
							tamDTO.setType("ForumService");
						}else if(tam instanceof AnnouncementService){
							tamDTO.setType("AnnouncementService");
						}else if(tam instanceof ChatService){
							tamDTO.setType("ChatService");
						}else if(tam instanceof SentMailService){
							tamDTO.setType("SentMailService");
						}
						tamsDTOHash.put(tam.getId(), tamDTO);
					}
				}
			}else{
				for(ToolAndMaterial tam : uolTams){
					ToolsAndMaterialsDTO tamDTO = new ToolsAndMaterialsDTO();
					tamDTO.setText(tam.getTitle());
					tamDTO.setId(String.valueOf(tam.getId()));
					tamDTO.setEnable(false);
					if(tam instanceof LearningObject){
						tamDTO.setType("LearningObject");
					}else if(tam instanceof ForumService){
						tamDTO.setType("ForumService");
					}else if(tam instanceof AnnouncementService){
						tamDTO.setType("AnnouncementService");
					}else if(tam instanceof ChatService){
						tamDTO.setType("ChatService");
					}else if(tam instanceof SentMailService){
						tamDTO.setType("SentMailService");
					}
					tamsDTOHash.put(tam.getId(), tamDTO);
				}
			}
			Iterator<ToolsAndMaterialsDTO> it = tamsDTOHash.values().iterator();
			while(it.hasNext()){
				tamDTOs.add((ToolsAndMaterialsDTO) it.next());
			}
		}else{
			List<ToolAndMaterial> actToolAndMaterials = new ArrayList<ToolAndMaterial>();
			for(int i=0;i<data.size();){
				ToolsAndMaterialsDTO tamsDTO = new ToolsAndMaterialsDTO();
				tamsDTO.setType(data.get(i++));
				tamsDTO.setText(data.get(i++));
				tamsDTO.setEnable(Boolean.valueOf(data.get(i++)));
				tamDTOs.add(tamsDTO);
			}
			for(ToolsAndMaterialsDTO dto : tamDTOs){
				if("LearningObject".equals(dto.getType()) && dto.isEnable()){
					LearningObject learningObject = (LearningObject)toolAndMaterialService.getTaMByUoFandTamName(dto.getText(), unitOfLearningId);
					actToolAndMaterials.add(learningObject);
				}else if("ForumService".equals(dto.getType()) && dto.isEnable()){
					ForumService forumService = (ForumService)toolAndMaterialService.getTaMByUoFandTamName(dto.getText(), unitOfLearningId);
					actToolAndMaterials.add(forumService);
				}else if("AnnouncementService".equals(dto.getType()) && dto.isEnable()){
					AnnouncementService announcementService = (AnnouncementService)toolAndMaterialService.getTaMByUoFandTamName(dto.getText(), unitOfLearningId);
					actToolAndMaterials.add(announcementService);
				}else if("ChatService".equals(dto.getType()) && dto.isEnable()){
					ChatService chatService = (ChatService)toolAndMaterialService.getTaMByUoFandTamName(dto.getText(), unitOfLearningId);
					actToolAndMaterials.add(chatService);
				}else if("SentMailService".equals(dto.getType()) && dto.isEnable()){
					SentMailService sentMailService = (SentMailService)toolAndMaterialService.getTaMByUoFandTamName(dto.getText(), unitOfLearningId);
					actToolAndMaterials.add(sentMailService);
				}
			}
			activity.setTams(actToolAndMaterials);
			activityService.save(activity);
		}

		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		modelMap.put("items", tamDTOs);
		modelMap.put("total", tamDTOs.size());
		modelMap.put("success", true);

		return modelMap;
	}
	
	
	@RequestMapping(value="jsp/tam/saGrid.action")
	public @ResponseBody Map<String, Object> saGridObject(
			HttpSession session,
			@RequestParam(value="limit",required=false) Integer limit,
			@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="start",required=false) Integer start,
			@RequestParam(value="data",required=false) List<String> data) throws Exception {

		int unitOfLearningId = (Integer)session.getAttribute("unitOfLearningId");
		String activityId = (String)session.getAttribute("graphId");
		String[] activityType = activityId.split(":");
		Activity activity = activityService.getbyGraphId(activityType[1]);
		List<ToolAndMaterial> uolTams = toolAndMaterialService.getTamByUoL(unitOfLearningId);
		List<ToolAndMaterial> activityTams = new ArrayList<ToolAndMaterial>();
		HashMap<Integer, ToolsAndMaterialsDTO> tamsDTOHash = new HashMap<Integer, ToolsAndMaterialsDTO>();
		if(!activity.getTams().isEmpty()){
			activityTams = activity.getTams();
		}
		
		List<ToolsAndMaterialsDTO> tamDTOs = new ArrayList<ToolsAndMaterialsDTO>();
		if(data==null){//just view them
			if(!activityTams.isEmpty()){
				for(ToolAndMaterial tam : activityTams){
					ToolsAndMaterialsDTO tamDTO = new ToolsAndMaterialsDTO();
					tamDTO.setText(tam.getTitle());
					tamDTO.setId(String.valueOf(tam.getId()));
					tamDTO.setEnable(true);
					if(tam instanceof LearningObject){
						tamDTO.setType("LearningObject");
					}else if(tam instanceof ForumService){
						tamDTO.setType("ForumService");
					}else if(tam instanceof AnnouncementService){
						tamDTO.setType("AnnouncementService");
					}else if(tam instanceof ChatService){
						tamDTO.setType("ChatService");
					}else if(tam instanceof SentMailService){
						tamDTO.setType("SentMailService");
					}
					tamsDTOHash.put(tam.getId(), tamDTO);
				}
				
				for(ToolAndMaterial tam : uolTams){
					if(!tamsDTOHash.containsKey(tam.getId())){
						ToolsAndMaterialsDTO tamDTO = new ToolsAndMaterialsDTO();
						tamDTO.setText(tam.getTitle());
						tamDTO.setId(String.valueOf(tam.getId()));
						tamDTO.setEnable(false);
						if(tam instanceof LearningObject){
							tamDTO.setType("LearningObject");
						}else if(tam instanceof ForumService){
							tamDTO.setType("ForumService");
						}else if(tam instanceof AnnouncementService){
							tamDTO.setType("AnnouncementService");
						}else if(tam instanceof ChatService){
							tamDTO.setType("ChatService");
						}else if(tam instanceof SentMailService){
							tamDTO.setType("SentMailService");
						}
						tamsDTOHash.put(tam.getId(), tamDTO);
					}
				}
			}else{
				for(ToolAndMaterial tam : uolTams){
					ToolsAndMaterialsDTO tamDTO = new ToolsAndMaterialsDTO();
					tamDTO.setText(tam.getTitle());
					tamDTO.setId(String.valueOf(tam.getId()));
					tamDTO.setEnable(false);
					if(tam instanceof LearningObject){
						tamDTO.setType("LearningObject");
					}else if(tam instanceof ForumService){
						tamDTO.setType("ForumService");
					}else if(tam instanceof AnnouncementService){
						tamDTO.setType("AnnouncementService");
					}else if(tam instanceof ChatService){
						tamDTO.setType("ChatService");
					}else if(tam instanceof SentMailService){
						tamDTO.setType("SentMailService");
					}
					tamsDTOHash.put(tam.getId(), tamDTO);
				}
			}
			Iterator<ToolsAndMaterialsDTO> it = tamsDTOHash.values().iterator();
			while(it.hasNext()){
				tamDTOs.add((ToolsAndMaterialsDTO) it.next());
			}
		}else{
			List<ToolAndMaterial> actToolAndMaterials = new ArrayList<ToolAndMaterial>();
			for(int i=0;i<data.size();){
				ToolsAndMaterialsDTO tamsDTO = new ToolsAndMaterialsDTO();
				tamsDTO.setType(data.get(i++));
				tamsDTO.setText(data.get(i++));
				tamsDTO.setEnable(Boolean.valueOf(data.get(i++)));
				tamDTOs.add(tamsDTO);
			}
			for(ToolsAndMaterialsDTO dto : tamDTOs){
				if("LearningObject".equals(dto.getType()) && dto.isEnable()){
					LearningObject learningObject = (LearningObject)toolAndMaterialService.getTaMByUoFandTamName(dto.getText(), unitOfLearningId);
					actToolAndMaterials.add(learningObject);
				}else if("ForumService".equals(dto.getType()) && dto.isEnable()){
					ForumService forumService = (ForumService)toolAndMaterialService.getTaMByUoFandTamName(dto.getText(), unitOfLearningId);
					actToolAndMaterials.add(forumService);
				}else if("AnnouncementService".equals(dto.getType()) && dto.isEnable()){
					AnnouncementService announcementService = (AnnouncementService)toolAndMaterialService.getTaMByUoFandTamName(dto.getText(), unitOfLearningId);
					actToolAndMaterials.add(announcementService);
				}else if("ChatService".equals(dto.getType()) && dto.isEnable()){
					ChatService chatService = (ChatService)toolAndMaterialService.getTaMByUoFandTamName(dto.getText(), unitOfLearningId);
					actToolAndMaterials.add(chatService);
				}else if("SentMailService".equals(dto.getType()) && dto.isEnable()){
					SentMailService sentMailService = (SentMailService)toolAndMaterialService.getTaMByUoFandTamName(dto.getText(), unitOfLearningId);
					actToolAndMaterials.add(sentMailService);
				}
			}
			activity.setTams(actToolAndMaterials);
			activityService.save(activity);
		}

		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		modelMap.put("items", tamDTOs);
		modelMap.put("total", tamDTOs.size());
		modelMap.put("success", true);

		return modelMap;
	}

	public IUnitOfLearningService getUnitOfLearningService() {
		return unitOfLearningService;
	}
	@Resource(name="unitOfLearningService")
	public void setUnitOfLearningService(IUnitOfLearningService unitOfLearningService) {
		this.unitOfLearningService = unitOfLearningService;
	}

	public IRoleService getRoleService() {
		return roleService;
	}
	@Resource(name="roleService")
	public void setRoleService(IRoleService roleService) {
		this.roleService = roleService;
	}

	public IToolAndMaterialService getToolAndMaterialService() {
		return toolAndMaterialService;
	}
	@Resource(name="toolAndMaterialService")
	public void setToolAndMaterialService(
			IToolAndMaterialService toolAndMaterialService) {
		this.toolAndMaterialService = toolAndMaterialService;
	}
	public IActivityService getActivityService() {
		return activityService;
	}
	@Resource(name="activityService")
	public void setActivityService(IActivityService activityService) {
		this.activityService = activityService;
	}


}
